if (isDedicated) exitWith {};

private ["_unit","_class","_cfgDefault","_cfg","_text","_submenu","_expression","_icon","_cursor","_enable","_itemID","_removeAfterExpressionCall","_menu","_isDuplicate"];
_text = _this select 0;
_expression = _this select 1;
_unit = player;

_submenu = "";
_icon = "";
_cursor = "";
_enable = "true";

//--- Terminate when the menu is full
_menu = _unit getvariable ["BIS_fnc_addCommMenuItem_menu",[]];
if (isnil "_menu") then { _menu = []; };
if (count _menu >= 10) exitwith {"Cannot add comm menu item, the menu is full. Maximum number of 10 items is allowed." call bis_fnc_error; -1};

//--- Get a unique item ID
_itemID = count _menu;

//--- Register the item
_menu set [
	count _menu,
	[
		_itemID,
		_text,
		_submenu,
		_expression,
		_enable,
		_cursor,
		_icon
	]
];
_unit setvariable ["BIS_fnc_addCommMenuItem_menu",_menu];

//--- Execute constant loop for refreshing the menu when player object changed (e.g., upon team switch)
if (isnil {BIS_fnc_addCommMenuItem_loop}) then {
	BIS_fnc_addCommMenuItem_loop = [] spawn {
		scriptname "BIS_fnc_addCommMenuItem_loop";
		_player = objnull;
		while {true} do {
			waituntil {
				sleep 0.1;
				player != _player
			};
			[] call bis_fnc_refreshCommMenu;
			_player = player;
		};
	};
};

//--- Restore the icons upon game load
if (isnil {BIS_fnc_addCommMenuItem_load}) then {
	BIS_fnc_addCommMenuItem_load = addmissioneventhandler ["loaded",{[] call bis_fnc_refreshCommMenu;}];
};

if (_unit == player) then {
	//--- Refresh the menu and icons
	[] call bis_fnc_refreshCommMenu;
	//--- Close the menu when opened
	if (commandingmenu == "#User:BIS_fnc_addCommMenuItem_menu") then {showcommandingmenu "";};
};

_itemID